/*************************************************************************
	> File Name: leetcode23.合并K个升序链表_v1.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 五  9/24 17:21:27 2021
 ************************************************************************/

//顺序合并
//时间复杂度：O(k^2 x n)
//空间复杂度：O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if (l1 == nullptr || l2 == nullptr) return l1 ? l1 : l2;
        ListNode *head = new ListNode(0);
        ListNode *pre = head;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                pre->next = l1;
                l1 = l1->next;
            } else {
                pre->next = l2;
                l2 = l2->next;
            }
            pre = pre->next;
        }
        pre->next = l1 ? l1 : l2;
        return head->next;
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode *ans = nullptr;
        for (size_t i = 0; i < lists.size(); i++) {
            ans = mergeTwoLists(ans, lists[i]);
        }
        return ans;
    }
};
